/**
 * @Desciption 系统后台元数据视图配置JS-systemDataView.jsp
 * @Author guoyanfei
 */
//项目路径
var strPath = window.document.location.pathname;
//var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);
var postPath = "/gdp";
var systemDataView = systemDataView || {};
var cfgtable = "";

// 记录显示列表
var showFieldList = {};
var relationshipList = [];
var pointList = {};

systemDataView.prototype = {
    init: function () {//初始化
        jsPlumb.ready(function () {
            systemDataView.prototype.initData();//左侧树初始化
            systemDataView.prototype.tabDataView();//视图信息配置选项卡初始化
            systemDataView.prototype.tabFieldConfig();//关联表配置选项卡初始化
            systemDataView.prototype.allEventFieldConfig();//关联表配置维护事件
            systemDataView.prototype.tabShowField();//显示字段配置选项卡初始化
            systemDataView.prototype.eventFieldaddnosSave();//显示字段保存事件
            systemDataView.prototype.tabShowData();//数据预览选项卡初始化
            systemDataView.prototype.multiSelectAll();//显示列全选
            systemDataView.prototype.multiDeselectAll();//显示列反选
            systemDataView.prototype.associationTable();// 关联表配置
        });
    },
    initData: function(){
        //初始化
        var ismark = GetQueryString("ismark");
        var dbkey = GetQueryString("dbkey");
        var dtConfigId = GetQueryString("dtConfigId");

        //测试数据源连接
        function testDataconn(dbKey) {
            var result = false;
            $.ajax({
                url: postPath + "/system/dataConfig/testDataConnection",
                type: "POST",
                data: {dbKey: dbKey},
                async: false,
                success: function (res) {
                    result = res;
                }
            });
            return result;
        }

        if (ismark == "1") {
            //新增视图
            if (!testDataconn(dbkey)) {
                bootbox.alert("数据源连接失败,请检测数据源连接!")
                return;
            }
            $("#dtConn").val(dbkey);
            $("#hid_dbkey").val(dbkey);
            systemDataView.prototype.bingDataTable(dbkey);
            $("#hid_IsMark").val(ismark);
        } else if (ismark == "2") {
            //修改视图
            $.ajax({
                type: 'POST',
                url: postPath + '/system/dataView/getTabelInfobyConfigid',
                data: {dtConfigId: dtConfigId, tableType: "2"},
                async: false,
                success: function (res) {
                    cfgtable = res;
                }
            });
            if (!testDataconn(cfgtable.dtConn)) {
                bootbox.alert("数据源连接失败,请检测数据源连接!")
                return;
            }
            systemDataView.prototype.bingDataTable(cfgtable.dtConn);
            $("#dtName").val(cfgtable.dtName).trigger("change");
            $("#dtConfigId").val(cfgtable.dtConfigId);
            $("#dtNameCn").val(cfgtable.dtNameCn);
            $("#dtOrder").val(cfgtable.dtOrder);
            $("#dtConn").val(cfgtable.dtConn);
            $("#dtPrimarykey").val(cfgtable.dtPrimarykey);
            $("#dtRemark").val(cfgtable.dtRemark);
            $("#hid_dtguid").val(cfgtable.guid);
            $("#hid_dtConfigId").val(cfgtable.dtConfigId);
            $("#dtName").attr("disabled", "disabled");
            $("#dtConfigId").attr("disabled", "disabled");
            $("#hid_dbkey").val(cfgtable.dtConn);
            $("#hid_IsMark").val(ismark);
            $("#mastertable").val(cfgtable.dtNameCn.substring(0, cfgtable.dtNameCn.length - 2) + "(" + cfgtable.dtName + ")");
            systemDataView.prototype.getExtendFieldAddons();

            $.getJSON(postPath + '/system/dataView/getFieldConfigBypage', {
                pageNo: 1,
                pageSize: 100,
                dtConfigId: $("#hid_dtConfigId").val()
            }).done(function (res) {
                var $association = $("#association-table");
                $.each(res.rows, function (index, data) {
                    bindAssociation(data.foreignTable, function () {
                        var sourceId = $association.find("option[value='" + data.tableName + "']").attr('dtName') + '-' + data.fieldid;
                        var targetId = $association.find("option[value='" + data.foreignTable + "']").attr('dtName') + '-' + data.foreignCode;
                        connectField(sourceId, targetId);
                        hideConnect();
                    });
                });
            });

        }

    },
    bingDataTable(dtconn) {//视图信息配置-绑定数据源视图
        var strTabletxt = "";
        $("#dtName").empty();
        $.ajax({
            type: 'POST',
            url: postPath + '/system/dataView/getTableList',
            data: {dbkey: dtconn},
            async: false,
            success: function (data) {
                $.each(data, function (i, e) {
                    var strtxt = "<option value=" + e.dtConfigId + ">" + e.dtName;
                    if (e.dtNameCn != null && e.dtNameCn != "" && e.dtNameCn != "undefined") {
                        strtxt += "(" + e.dtNameCn + ")";
                    }
                    strtxt += "</option>";
                    strTabletxt += strtxt;
                });
                $("#dtName").append("<option>请选择表</option>");
                $("#dtName").append(strTabletxt);
            }

        });
        systemDataView.prototype.eventDtnameChange();
    },
    tabDataView: function () {//视图信息配置选项卡初始化
        $("#dtName").select2();//数据源视图-设置筛选功能
        systemDataView.prototype.eventSaveViewData();//保存视图信息
    },
    eventDtnameChange: function () {//视图信息配置-数据源视图改变事件
        $("#dtName").click(function () {
            $.ajax({
                type: 'POST',
                url: postPath + '/system/dataView/getTabelInfobyConfigid',
                data: {dtConfigId: $("#dtName").val(), tableType: "1"},
                success: function (data) {
                    //视图排序字段处理，新增固定别名AA
                    var orderfields = "";
                    if (data.dtOrder != null && data.dtOrder != "") {
                        var orders = data.dtOrder.split(",");
                        $.each(orders, function (i, e) {
                            if (orderfields == "") {
                                orderfields = data.dtName+"." + e;
                            } else {
                                orderfields += "," + data.dtName + "." + e;
                            }
                        });
                    }
                    $("#dtOrder").val(orderfields);
                    $("#dtPrimarykey").val(data.dtPrimarykey);
                    $("#dtConfigId").val($("#hid_dbkey").val() + "_" + data.dtName + "_VIEW");
                    $("#dtNameCn").val(data.dtNameCn + "视图");
                    if (data.dtRemark == null || data.dtRemark == "") {
                        $("#dtRemark").val("视图");
                    } else {
                        $("#dtRemark").val(data.dtRemark + "视图");
                    }

                }
            });
        });
    },
    eventSaveViewData: function () {//视图信息配置-保存视图信息
        $("#btn_tableSave").click(function () {
            var validresult = systemDataView.prototype.validViewInfo();
            var saveUrl = "";
            if ($("#hid_IsMark").val() == "1") {
                saveUrl = postPath + '/system/dataView/add';
            } else {
                saveUrl = postPath + '/system/dataView/update';
            }
            if (validresult) {
                var pp = {
                    dtName: $("#dtName").val(),
                    dtConfigId: $("#dtConfigId").val(),
                    dtNameCn: $("#dtNameCn").val(),
                    dtOrder: $("#dtOrder").val(),
                    dtConn: $("#dtConn").val(),
                    dtPrimarykey: $("#dtPrimarykey").val(),
                    dtRemark: $("#dtRemark").val(),
                    guid: $("#hid_dtguid").val()
                }
                $.ajax({
                    type: 'POST',
                    url: saveUrl,
                    async: false,
                    data: JSON.stringify(pp),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (res) {
                        if (res > 0) {
                            if ($("#hid_IsMark").val() == "1") {
                                $("#hid_IsMark").val(2);
                                $("#dtName").attr("disabled", "disabled");
                                $("#dtConfigId").attr("disabled", "disabled");
                                $.ajax({
                                    type: 'POST',
                                    url: postPath + '/system/dataView/getTabelInfobyConfigid',
                                    data: {dtConfigId: $("#dtConfigId").val(), tableType: "2"},
                                    async: false,
                                    success: function (res) {
                                        $("#hid_dtguid").val(res.guid);
                                    }
                                });
                            }
                            showMsg("保存成功!", "success");
                            $("#hid_dtConfigId").val($("#dtConfigId").val());
                            $("#mastertable").val($("#dtNameCn").val().substring(0, $("#dtNameCn").val().length - 2) + "(" + $("#dtName").val() + ")");
                            initMasterTable();
                        } else {
                            showMsg("保存失败,请刷新后重试!", "error");
                        }
                    }
                });
            }
        });
    },
    validViewInfo: function () {//视图信息配置-视图信息验证
        if ($("#dtName").val() == "") {
            $("#valide_dtMessage").html("数据源视图不能为空,请选择!");
            return false;
        } else {
            $("#valide_dtMessage").html("");
        }

        if ($("#dtConfigId").val() == "") {
            $("#valide_dtMessage").html("视图标识不能为空,请输入!");
            return false;
        } else {
            if ($("#hid_IsMark").val() == "1") {
                var dtConfignum = 0;
                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/dataView/getdtConfigId',
                    data: {dtConfigId: $("#dtConfigId").val()},
                    async: false,
                    dataType: 'json',
                    success: function (num) {
                        dtConfignum = num;
                    }
                });
                if (dtConfignum > 0) {
                    $("#valide_dtMessage").html("视图标识已存在，请重新输入!");
                    return false;
                } else {
                    $("#valide_dtMessage").html("");
                }
            } else {
                $("#valide_dtMessage").html("");
            }
        }

        if ($("#dtNameCn").val() == "") {
            $("#valide_dtMessage").html("请输入视图中文名称!");
            return false;
        } else {
            $("#valide_dtMessage").html("");
        }

        if ($("#dtOrder").val() == "") {
            $("#valide_dtMessage").html("请输入视图排序字段!");
            return false;
        } else {
            $("#valide_dtMessage").html("");
        }

        if ($("#dtConn").val() == "") {
            $("#valide_dtMessage").html("请输入数据源标识!");
            return false;
        } else {
            $("#valide_dtMessage").html("");
        }

        if ($("#dtRemark").val() == "") {
            $("#valide_dtMessage").html("请输入视图说明信息!");
            return false;
        } else {
            $("#valide_dtMessage").html("");
        }

        return true;
    },
    cleanViewInfo: function () {//清空视图信息
        $("#dtName").select2("val", "");
        $("#dtConfigId").val("");
        $("#dtNameCn").val("");
        $("#dtOrder").val("");
        $("#dtConn").val("");
        $("#dtPrimarykey").val("");
        $("#dtRemark").val("");
        $("#hid_IsMark").val("");
        $("#hid_dtguid").val("");
        $("#hid_dtConfigId").val("");
        $("#dtName").removeAttr("disabled");
        $("#dtConfigId").removeAttr("disabled");
    },
    locationTab: function () {//定位默认视图信息选项卡
        $('#myTab a[href="#tab_1_1_1"]').tab('show');
    },
    tabFieldConfig: function () {//关联表配置-关联表配置选项卡初始化
        $("#a_tab_fieldconfig").click(function () {
            var dtConfigId = $("#hid_dtConfigId").val();
            if (dtConfigId == "") {
                bootbox.alert("请先设置视图信息!");
                setTimeout(systemDataView.prototype.locationTab, 200);
                return;
            }
            $('#tab_left a[href="#tab_2_1"]').tab('show');
            systemDataView.prototype.getFieldConfigList();
            systemDataView.prototype.bindFieldConfigPrimaryField();
            systemDataView.prototype.bindFieldConfigTable();

            $("#foreignTable").select2();
            $('#fieldid').select2();
            $('#foreignCode').select2();
        });
    },
    allEventFieldConfig: function () {//关联表配置维护事件
        systemDataView.prototype.eventFieldConfigSave();
        systemDataView.prototype.eventFieldConfigEdit();
        systemDataView.prototype.eventFieldConfigDel();
        $("#a_fieldconfig_2_2").on("click", systemDataView.prototype.eventFieldConfigclean);
    },
    getFieldConfigList: function () {//关联表配置-关联表数据列表
        $("#tb_fieldConfigList").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/dataView/getFieldConfigBypage',
            undefinedText: '-',
            pagination: true, // 分页
            striped: true, // 是否显示行间隔色
            queryParams: queryFieldConfigParams,
            cache: false, // 是否使用缓存
            pageList: [5, 10, 20],
            toolbar: "#toolbar_fieldconfig",// 指定工具栏
            showColumns: false, // 显示隐藏列
            showRefresh: false, // 显示刷新按钮
            uniqueId: "guid", // 每一行的唯一标识
            sidePagination: "server", // 服务端处理分页
            columns: [{
                field: 'state',
                checkbox: true,
                align: 'center',
                valign: 'middle'
            }, {
                title: '主表',
                field: 'tableName',
                align: 'center',
                valign: 'middle'
            }, {
                title: '主表字段',
                field: 'fieldid',
                align: 'center',
                valign: 'middle'
            }, {
                title: '外键类型',
                field: 'foreignType',
                align: 'center',
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == "1") {
                        return "表连接";
                    } else if (value == "2") {
                        return "枚举";
                    }
                }
            }, {
                title: '关联关系',
                field: 'relationType',
                align: 'center',
                valign: 'middle',
                formatter: function (value, row, index) {
                    if (value == "1") {
                        return "内连接";
                    } else if (value == "2") {
                        return "左连接";
                    } else if (value == "3") {
                        return "右连接";
                    }
                }
            }, {
                title: '关联表',
                field: 'foreignTable',
                align: 'center',
                valign: 'middle'
            }, {
                title: '关联表字段',
                field: 'foreignCode',
                align: 'center',
                valign: 'middle'
            }, {
                title: '表别名',
                field: 'altername',
                align: 'center',
                valign: 'middle'
            }, {
                title: '备注',
                field: 'remark',
                align: 'center',
                valign: 'middle'
            }]
        });

        //关联表配置-关联表参数
        function queryFieldConfigParams(pageReqeust) {
            var temp = {
                pageNo: pageReqeust.offset / pageReqeust.limit + 1,
                pageSize: pageReqeust.limit,
                dtConfigId: $("#hid_dtConfigId").val()
            };
            return temp;
        }

    },
    bindFieldConfigPrimaryField: function () {//关联表配置-绑定主表字段
        $("#fieldid").html("");
        $.ajax({
            type: "post",
            url: postPath + '/system/dataView/getFieldBydtConfigId',
            data: {dtConfigId: $("#hid_dtConfigId").val()},
            async: false,
            success: function (data) {
                $.each(data, function (key, value) {
                    $("#fieldid").append("<option value='" + value.dfName + "'>" + value.dfNameCn + "(" + value.dfName + ")" + "</option>");
                });
            }
        });
    },
    bindFieldConfigTable: function () {//关联表配置-绑定外键表信息
        //绑定外键表信息
        $("#foreignTable").html("");
        $.ajax({
            type: "post",
            url: postPath + '/system/dataView/getTableList',
            data: {dbkey: $("#hid_dbkey").val()},
            async: false,
            success: function (data) {
                $("#foreignTable").append("<option value=''>请选择</option>");
                $.each(data, function (key, value) {
                    $("#foreignTable").append("<option value='" + value.dtConfigId + "'>" + value.dtNameCn + "(" + value.dtConfigId + ")" + "</option>");
                });
            }
        });
        $("#foreignTable").change(function () {
            systemDataView.prototype.bindFieldConfigField();
        });
    },
    bindFieldConfigField: function () {//绑定外键表字段
        $("#foreignCode").val(null).trigger("change");
        $("#foreignCode").html("");
        $.ajax({
            type: "post",
            url: postPath + '/system/dataView/getFieldByConfigId',
            data: {dtConfigId: $("#foreignTable").val()},
            async: false,
            success: function (data) {
                $.each(data, function (key, value) {
                    $("#foreignCode").append("<option value='" + value.dfName + "'>" + value.dfNameCn + "(" + value.dfName + ")" + "</option>");
                });
            }
        });
    },
    eventFieldConfigSave: function () {//关联表配置-保存
        $("#btn_fieldConfigSave").click(function () {
            var result = systemDataView.prototype.validateFieldConfig();
            if (result == false) {
                return;
            }
            var fieldids = $("#fieldid").val().join(",");
            var foreignCodes = $("#foreignCode").val().join(",");
            var temp = {
                "guid": $("#hid_fieldconfigid").val(),
                "fieldid": fieldids,
                "foreignType": '1',
                "relationType": $("#relationType").val(),
                "foreignCode": foreignCodes,
                "remark": $("#fieldConfigremark").val(),
                "foreignTable": $("#foreignTable").val(),
                "enumvalue": '',
                "dtConfigId": $("#hid_dtConfigId").val()
            };

            $.ajax({
                type: "POST",
                url: postPath + '/system/dataView/editFieldConfigInfo',
                data: JSON.stringify(temp),
                dataType: 'json',
                contentType: "application/json",
                success: function (data) {
                    if (data > 0) {
                        showMsg("保存成功!", "success");
                        $("#tb_fieldConfigList").bootstrapTable('refresh');
                        $('#tab_left a[href="#tab_2_1"]').tab('show');
                        systemDataView.prototype.eventFieldConfigclean();
                    } else {
                        showMsg("保存失败,请刷新后重试!", "error");
                    }
                },
                error: function () {
                    showMsg("保存失败,请刷新后重试!", "error");
                }
            });

        });

    },
    eventFieldConfigEdit: function () {//关联表配置-修改操作
        $("#btn_fieldconfigEndit").click(function () {
            var row = $('#tb_fieldConfigList').bootstrapTable('getSelections');
            if (row == null || row == "") {
                bootbox.alert("请选择一行!");
                return;
            }
            var fieldids = row[0].fieldid.split(',');
            var foreignCodes = row[0].foreignCode.split(',');
            $("#hid_fieldconfigid").val(row[0].guid);
            $("#fieldid").val(fieldids).trigger("change");
            $("#relationType").val(row[0].relationType);
            $("#foreignTable").val(row[0].foreignTable).trigger("change");
            ;
            systemDataView.prototype.bindFieldConfigField();
            $("#foreignCode").val(foreignCodes).trigger("change");
            $("#fieldConfigremark").val(row[0].remark);
            $('#tab_left a[href="#tab_2_2"]').tab('show');

        });
    },
    validateFieldConfig: function () {//关联表配置-验证信息
        if ($("#foreignTable").val() == "") {
            $("#valide_fieldConfigMessage").html("关联表不能为空!");
            return false;
        } else {
            $("#valide_fieldConfigMessage").html("");
        }

        if ($("#fieldid").val() == null || $("#fieldid").val() == "") {
            $("#valide_fieldConfigMessage").html("主表字段不能为空!");
            return false;
        } else {
            $("#valide_fieldConfigMessage").html("");
        }

        if ($("#foreignCode").val() == null || $("#foreignCode").val() == "") {
            $("#valide_fieldConfigMessage").html("关联字段不能为空!");
            return false;
        } else {
            $("#valide_fieldConfigMessage").html("");
        }

        return true;
    },
    eventFieldConfigDel: function () {//关联表配置-删除关联表操作
        $("#btn_fieldconfigDel").click(function () {
            var row = $('#tb_fieldConfigList').bootstrapTable('getSelections');
            if (row == null || row == "") {
                bootbox.alert("请选择一行!");
                return;
            }
            bootbox.confirm("确认删除?", function (result) {
                if (result == false)
                    return;
                var keys = "";
                $.each(row, function (i, e) {
                    keys += e.guid + ",";
                });
                keys = keys.substring(0, keys.length - 1);
                $.ajax({
                    url: postPath + '/system/dataView/batchDelInfo',
                    type: 'POST',
                    data: {guids: keys},
                    success: function (data) {
                        showMsg("删除成功!", "success");
                        $('#tb_fieldConfigList').bootstrapTable('refresh');
                    },
                    error: function () {
                        showMsg("删除失败!","error");
                    }
                });
            });

        });
    },
    eventFieldConfigclean: function () {//关联表清空信息
        $("#fieldid").val(null).trigger("change");
        $("#relationType").val("");
        $("#foreignTable").val("");
        $("#foreignCode").val(null).trigger("change");
        $("#foreignName").val("");
        $("#fieldConfigremark").val("");
        $("#hid_fieldconfigid").val("");
    },
    tabShowField: function () {//显示字段配置-显示字段配置初始化
        $("#a_tab_fieldaddons").click(function () {
            var dtConfigId = $("#hid_dtConfigId").val();
            if (dtConfigId == "") {
                bootbox.alert("请先设置视图信息!");
                setTimeout(systemDataView.prototype.locationTab, 200);
                return;
            }
            systemDataView.prototype.eventextendFieldAddons();
        });
    },
    multiSelectAll: function () {
        $("#btn_selectAll").click(function () {
            $('#my_multi_select2').multiSelect('select_all');
        });
    },
    multiDeselectAll: function () {
        $("#btn_deselectAll").click(function () {
            $('#my_multi_select2').multiSelect('deselect_all');
        });
    },
    eventFieldaddnosSave: function () {//显示字段配置-勾选显示列-保存操作
        $("#btn_FieldaddnosSave").click(function () {
            var strFieldguid = "";
            var strFieldtxt = [];
            $(".ms-selection").find(".ms-selected").each(function (i, e) {
                strFieldguid += $(this).attr("customvalue") + "&" + $(this).attr("primaryField") + "&" + $(this).attr("isenum") + ",";
                var fieldtxt = $(this).find("span").text();
                strFieldtxt.push(fieldtxt.substring(fieldtxt.indexOf("(") + 1, fieldtxt.lastIndexOf(")")));
            });

            //提示有重复字段
            var message = "";
            var arry = systemDataView.prototype.arrayRepetition(strFieldtxt);
            if (arry.length > 0) {
                for (var i = 0; i < arry.length; i++) {
                    if (message == null || message == "") {
                        message = arry[i];
                    } else {
                        message += "," + arry[i];
                    }
                }
            }
            if (message != null && message != "") {
                $("#arrayMessage").html("提示：字段" + message + "有重复，请在定制表单中修改重复字段!");
            }

            strFieldguid = strFieldguid.substring(0, strFieldguid.length - 1);
            $.ajax({
                url: postPath + '/system/dataView/insertFieldAddons',
                type: 'POST',
                async: false,
                data: {dtconfigid: $("#hid_dtConfigId").val(), guids: strFieldguid},
                success: function (data) {
                    showMsg("保存成功!", "success");
                }
            });

        });
    },
    arrayRepetition: function (ary1) {//数组去重复
        var ary = ary1.sort();//数组排序
        var cffwxmsAry = new Array();

        //所有重复元素添加进新数组内
        for (var i = 0; i < ary.length; i++) {
            if (ary[i] == ary[i + 1]) {
                cffwxmsAry.push(ary[i]);
            }

        }
        var result = [], isRepeated;

        //对重复元素数组进行元素去重
        for (var k = 0; k < cffwxmsAry.length; k++) {
            isRepeated = false;
            for (var j = 0; j < result.length; j++) {
                if (cffwxmsAry[k] == result[j]) {
                    isRepeated = true;
                    break;
                }
            }
            if (!isRepeated) {
                result.push(cffwxmsAry[k]);
            }
        }

        return result;
    },
    eventextendFieldAddons: function () {//显示字段配置-定制表单初始化
        $("#tb_fieldaddons").bootstrapTable('refresh');
        systemDataView.prototype.getExtendFieldAddons();
    },
    getExtendFieldAddons: function () {//显示字段配置-定制表单-查询已配置的列信息
        $("#tb_fieldaddons").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/dataView/getExtFieldAddonsListBydtconfig',
            undefinedText: '-',
            striped: true, // 是否显示行间隔色
            cache: false, // 是否使用缓存
            singleSelect: true,
            queryParams: {dtconfigid: $("#hid_dtConfigId").val()},
            uniqueId: "guid", // 每一行的唯一标识
            fixedColumns: false,
            fixedNumber: 1,
            responseHandler: function (res) {
                showFieldList = {};
                if (!!res) {
                    $.each(res, function (i, e) {
                        showFieldList[e.altername + '_' + e.fieldname ] = 'checked';
                    });
                    return res;
                }
                return [];
            },
            rowStyle: function (row, index) {
                var rows = $("#tb_fieldaddons").bootstrapTable('getData');
                var result = {};
                $.each(rows, function (i, e) {
                    if (row.guid != e.guid) {
                        if (e.fieldname == row.fieldname) {
                            result = {classes: 'warning'};
                        }
                    }
                });
                return result;
            },
            onLoadSuccess: function () {//当所有数据被加载时触发处理函数
                var data = $("#tb_fieldaddons").bootstrapTable('getData', true);//获取当前页数据
                mergeCells(data,'altername',0,$("#tb_fieldaddons"));
            },
            columns: [
                {
                    title: '表名',
                    field: 'altername',
                    align: 'center',
                    valign: 'middle'
                },
                 {
                title: '表字段',
                field: 'fieldname',
                align: 'center',
                valign: 'middle'
            }, {
                title: '中文名称',
                field: 'fieldnameCn',
                align: 'center',
                valign: 'middle'
            }, {
                    title: '字段类型',
                    field: 'fieldtype',
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '视图字段',
                    field: 'fieldname',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        return row.altername + '_' + value
                    }
                },{
                    title: '显示顺序',
                    field: 'showorder',
                    align: 'center',
                    valign: 'middle'
                }],
            // onCheck: systemDataView.prototype.editFieldAddons,
            // onUncheck: systemDataView.prototype.saveFieldAddons
        });
    },
    editFieldAddons: function (row) {//表单配置-定制表单-修改列信息
        $("#tb_fieldaddons").find("tr").each(function () {
            var trguid = $(this).attr("data-uniqueid");
            if (trguid == row.guid) {
                var nRow = $(this);
                var jqTds = $('>td', nRow);
                jqTds[3].innerHTML = '<select class="form-control input-small" style="width:62px !important;">'
                    + '<option ' + (row.ismodfcaption == 0 ? "selected='selected'" : "") + ' value="0">否</option>'
                    + '<option ' + (row.ismodfcaption == 1 ? "selected='selected'" : "") + ' value="1">是</option></select>';
                jqTds[4].innerHTML = '<input style="width:70px !important;" type="text" class="form-control input-small" value="' + (row.modifieldcaption == null ? "" : row.modifieldcaption) + '">';
                jqTds[5].innerHTML = '<input style="width:43px !important;" id="touchspin_1" type="text" value="' + (row.showorder == null ? "0" : row.showorder) + '">';

            }
        });
        $("#touchspin_1").TouchSpin({
            verticalbuttons: true
        });
    },
    saveFieldAddons: function (row) {//表单配置-定制表单-保存修改后的列信息
        $("#tb_fieldaddons").find("tr").each(function () {
            var trguid = $(this).attr("data-uniqueid");
            if (trguid == row.guid) {
                var nRow = $(this);
                var jqTds = $('>td', nRow);
                var midffvalue = $(':input', nRow);
                var temp = {
                    guid: row.guid,
                    ismodfcaption: midffvalue[1].value,
                    modifieldcaption: midffvalue[2].value,
                    showorder: midffvalue[3].value,
                };
                $.ajax({
                    type: 'POST',
                    url: postPath + '/system/dataView/updateFieldAddonns',
                    async: false,
                    data: JSON.stringify(temp),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (data) {
                        $("#tb_fieldaddons").bootstrapTable('refresh');
                    }
                });
            }
        });
    },
    tabShowData: function () {//数据预览选项卡初始化
        $("#a_tab_view").click(function () {
            var dtConfigId = $("#hid_dtConfigId").val();
            if (dtConfigId == "") {
                bootbox.alert("请先设置表信息!");
                setTimeout(systemDataView.prototype.locationTab, 200);
                return;
            }
            $("#tb_viewList").bootstrapTable('refresh');
            systemDataView.prototype.createTableShowData();
        });
    },
    createTableShowData: function () {//数据预览-生成表格
        var columns = [];
        //数据预览-创建表格
        $.ajax({
            url: postPath + '/system/dataView/getExtFieldAddonsListBydtconfig',
            type: 'POST',
            async: false,
            data: {dtconfigid: $("#hid_dtConfigId").val(), num: Math.random()},
            success: function (data) {
                $.each(data, function (i, e) {
                    var field = "";
                    var fieldCn = "";
                    if (e.ismodfname == 1) {
                        field = e.modifieldname;
                    } else {
                        field = e.altername + '_' + e.fieldname;
                    }
                    if (null != e.fieldnameCn && e.fieldnameCn != "" && e.fieldnameCn != "null") {
                        fieldCn = e.fieldnameCn;
                    } else {
                        fieldCn =  "(" + e.altername + ")"+ e.fieldname;
                    }

                    if (e.ismodfcaption == 1) {
                        fieldCn = e.modifieldcaption;
                    } else {
                        fieldCn =  "(" + e.altername + ")"+ e.fieldnameCn;
                    }
                    columns.push({"field": field, "title": fieldCn, "align": 'center', "valign": 'middle'});
                });
            },
            error: function () {
                showMsg("数据加载失败!","error");
            }
        });

        //数据预览-数据列表
        $("#tb_viewList").bootstrapTable('destroy').bootstrapTable({
            url: postPath + '/system/dataView/viewData',
            undefinedText: '-',
            pagination: true, // 分页
            striped: true, // 是否显示行间隔色
            queryParams: queryViewParams,
            cache: false, // 是否使用缓存
            pageList: [5, 10, 20],
            toolbar: "",// 指定工具栏
            showColumns: false, // 显示隐藏列
            showRefresh: false, // 显示刷新按钮
            uniqueId: "dbKey", // 每一行的唯一标识
            sidePagination: "server", // 服务端处理分页
            columns: columns
        });

        //数据预览-查询条件与分页数据
        function queryViewParams(pageReqeust) {
            var temp = {
                order: pageReqeust.order,
                pageNo: pageReqeust.offset / pageReqeust.limit + 1,
                pageSize: pageReqeust.limit,
                dtConfigId: $("#hid_dtConfigId").val()
            };
            return temp;
        }
    },
    // 关联表配置
    associationTable: function() {
        jsPlumb.importDefaults({
            DragOptions: {cursor: 'pointer', zIndex: 15},
            Container: $('#board').get(0),
            Endpoint: 'Image', // 端点类型
        });
        // 绑定连接监听
        jsPlumb.bind('connection', function (info) {
            var sourceId = info.sourceId;
            var targetId = info.targetId;
            var key = sourceId + '_' + targetId;
            jsPlumb.detach(info.connection);
            if (!!pointList[key]) return showMsg('当前关联已存在', 'warning');
            connectField(sourceId, targetId);
        });

        $('#a_tab_table, #a_tab_fieldconfig, #a_tab_fieldaddons, #a_tab_view').on('click',function () {
            hideConnect();
        });

        $('#a_tab_association').on('click', function (e) {
            var dtConfigId = $("#hid_dtConfigId").val();
            if (dtConfigId == "") {
                bootbox.alert("请先设置视图信息!");
                setTimeout(systemDataView.prototype.locationTab, 200);
                return;
            }
        });

        $('#a_tab_association').on('shown.bs.tab', function (e) {
            addEndpoint();
            // 显示关联表关系
            for (var i = 0; i < relationshipList.length; i++) {
                var lineArrElement = relationshipList[i];
                lineArrElement.show();
                lineArrElement.position();
            }
            // 绑定显示字段
            for (var field in showFieldList) {
                $('input:checkbox[field][name="'+ field +'"]').prop('checked', true);
            }
        });

        initMasterTable();

        // TODO: 添加关联表
        $('#btn-add-association').on('click', function () {
            var tableName = $('#association-table').val();
            if (tableName === '请选择关联表') return showMsg("请选择关联表!", "warning");
            if ($('tbody[dtName="' + tableName + '"]').length > 0) return showMsg("相同的表不能进行关联!", "warning");
            bindAssociation(tableName);
            addEndpoint();
        });

        // TODO: 保存关联
        $('#btn-save-association').on('click', function () {
            // TODO: 保存显示字段
            var strFieldguid = '';
            $.each($('tbody input:checkbox[field]:checked'), function (index, item) {
                strFieldguid += $(item).val() + '&' + $(item).attr('data-dtName')  + '&' +'0,'
            });
            strFieldguid = strFieldguid.substring(0, strFieldguid.length - 1);
            if(relationshipList.length === 0 && $('div.node').length > 1)  return showMsg("请建立关联表关系!", "warning");

            $ajax('/system/dataView/insertFieldAddons',
                {dtconfigid: $("#hid_dtConfigId").val(), guids: strFieldguid},
                function (data) {
                    systemDataView.prototype.getExtendFieldAddons();
                    showMsg("保存成功!", "success");
                });
            var relationField = [];
            for(var relation in pointList) {
                relationField.push(pointList[relation]);
            }
            $.ajax({
                type: "POST",
                url: postPath + '/system/dataView/editFieldConfigInfo/' + $("#hid_dtConfigId").val(),
                data: JSON.stringify(relationField),
                dataType: 'json',
                contentType: "application/json",
                success: function (data) {
                },
                error: function () {
                    showMsg("保存失败,请刷新后重试!", "error");
                }
            });
        });
    },
    getDataTableList: function($el) { // 获取关联表列表
        var strTabletxt = "";
        $el.empty();
        $.ajax({
            type: 'POST',
            url: postPath + '/system/dataView/getTableList',
            data: {dbkey: $("#hid_dbkey").val()},
            async: false,
            success: function (data) {
                $.each(data, function (i, e) {
                    var dtStr = '';
                    if (e.dtNameCn != null && e.dtNameCn != "" && e.dtNameCn != "undefined") {
                        dtStr = e.dtName + "(" + e.dtNameCn + ")";
                        if (e.dtConfigId === $("#dtName").val()) $("#primary-title").text(dtStr);
                    }
                    var strtxt = "<option value=" + e.dtConfigId + " dtName='"+ e.dtName +"' >" + dtStr + '</option>';
                    strTabletxt += strtxt;
                });
                $el.append("<option>请选择关联表</option>");
                $el.append(strTabletxt);
                $el.select2();
            }
        });
    },
    getFieldByConfigId: function (dtConfigId, func) {
        $.ajax({
            type: "post",
            url: postPath + '/system/dataView/getFieldByConfigId',
            data: {dtConfigId: dtConfigId},
            async: false,
            success: function (data) {
                func && func(data);
            }
        });
    }
}

function mergeCells(data,fieldName,colspan,target){
    //声明一个map计算相同属性值在data对象出现的次数和
    var sortMap = {};
    for(var i = 0 ; i < data.length ; i++){
        for(var prop in data[i]){
            if(prop == fieldName){
                var key = data[i][prop]     //fieldName的value
                if(sortMap.hasOwnProperty(key)){
                    sortMap[key] = sortMap[key] * 1 + 1;
                } else {
                    sortMap[key] = 1;
                }
                break;
            }
        }
    }
    //合并单元格
    var index = 0;
    for(var prop in sortMap){
        var count = sortMap[prop] * 1;
        $(target).bootstrapTable('mergeCells',{index:index, field:fieldName, colspan: colspan, rowspan: count});
        index += count;
    }
}

function initMasterTable(){
    // TODO: 绑定 table 列表
    systemDataView.prototype.getDataTableList($('#association-table'));
    // TODO: 绑定 主表 table 字段
    systemDataView.prototype.getFieldByConfigId($("#dtName").val(), function (result) {
        $('#primary-body').attr('dtName', $("#dtName").val());
        $('#primary-body').empty();
        $('#primary-body').append(fieldHtml(result));
        bindInputCheckbox();
        bindDraggable();
    });
}
function fieldHtml(result){
    var newHtml = '';
    $.each(result, function (index, item) {
        newHtml += '<tr id="'+ item.dtName +'-'+ item.dfName +'">';
        newHtml += '<td><input type="checkbox" name="' + item.dtName + '_'+ item.dfName +'" data-dtName="'+ item.dtName +'" value="'+ item.guid +'" field /></td>';
        newHtml += '<td>'+ item.dfName +'</td>';
        newHtml += '<td>'+ item.dfNameCn + '</td>';
        newHtml += '<td>'+ item.dtType +'</td>';
        newHtml += '<td>'+ (item.dfIsprimarykey === 1 ? '<i class="fa fa-check" aria-hidden="true"></i>':'') +'</td>';
        newHtml += '</tr>';
    })
    return newHtml;
}

function bindAssociation(tableName, func){
    systemDataView.prototype.getFieldByConfigId(tableName, function (result) {
        var newHtml = '<div class="col-md-4 node">';
        newHtml+= ' <div class="panel panel-primary">';
        newHtml+= '     <div class="panel-heading">'+
            $("#association-table").find("option[value='" + tableName + "']").text() +
            '<i class="fa fa-times pull-right" node-close style="cursor: pointer;font-size: 20px;"></i>' +
            // '<select relation-select class="form-control input-inline input-xsmall pull-right" style="margin-top: -8px; margin-right: 5px;">' +
            // '<option value="1">内连接</option>' +
            // '<option value="2">左连接</option>' +
            // '<option value="3">右连接</option>' +
            // '</select>'+
            '           </div>';
        newHtml+= '     <div class="panel-body">';
        newHtml+= '         <table class="table">';
        newHtml+= '             <thead><tr><th><input type="checkbox" selectedAll></th><th>字段标识</th><th>字段名</th><th>数据类型</th><th>主键</th></tr></thead>';
        newHtml+= '             <tbody dtName="'+ tableName +'" slave>' + fieldHtml(result) + '</tbody>';
        newHtml+= '         </table>';
        newHtml+= '     </div>';
        newHtml+= ' </div>';
        newHtml+= '</div>';

        if ($('tbody[dtName="'+ tableName +'"]').length === 0){
            $('#board').append(newHtml);
            bindInputCheckbox();
            bindDraggable();
            // 添加 删除关联表事件
            $('i[node-close]').on('click',function () {
                var $this =  $(this);
                bootbox.confirm('删除该表，其关联也将被删除，是否继续?', function (result) {
                    if (result) {
                        var trIds = [];
                        $this.parents('div.node').find('tbody tr').each(function (i, el) {
                            jsPlumb.removeAllEndpoints($(this));
                            trIds.push($(this).attr('id'));
                        });
                        removeAssociatio(trIds);
                        $this.parents('div.node').remove();
                    }
                });
            });

            // 绑定关联关系
            // $('select[relation-select]').on('change', function () {
            //     if (relationshipList.length === 0)  return;
            //     var $this = $(this);
            //     $this.parents('div.node').find('tbody tr').each(function (i, el) {
            //         for(var relation in pointList) {
            //             if (relation.indexOf($(el).attr('id')) > 0) {
            //                 pointList[relation].relationType = $this.find('option:selected').val();
            //                 console.log(pointList[relation]);
            //             }
            //         }
            //     });
            // });
        }
        func && func();
    });
}

function bindInputCheckbox(){
    // TODO: 全选事件
    $(':checkbox[selectedAll]').on('change', function () {
        $(this).parents('table')
            .find('tbody input:checkbox[field]')
            .prop('checked', $(this).is(':checked'))
        ;
    });
}

function bindDraggable(){
    var $draggable = $('.col-md-4').draggabilly({
        handle: '.panel-heading',
        containment: '#board',
    });

    $draggable.on('dragMove', function () {
        relationshipList.forEach(line => {
            line.position();
        });
        $(this).find('tbody tr').each(function (i, t) {
            jsPlumb.removeAllEndpoints($(this));
        });
    });
    $draggable.on('dragEnd', function () {
        addEndpoint();
    });
}

// 添加连接端点
function addEndpoint(){
    // 端点样式
    var endpoint = {
        endpoint: ['Image', { src: '../img/system/point.svg' }], //连接点的形状、大小
        // paintStyle: { fillStyle: '#0f0' }, //连接点的颜色
        scope: 'green dot', //点击该颜色的时候，其余该颜色的点都会显示虚线框
        connectorStyle: { strokeStyle: '#13227a', lineWidth: 6 }, //点与点之间连线颜色
        connector: ['Bezier', { curviness: 63 }], //线条形状，可弯曲
        maxConnections: -1, // 最大连接数
    };
    // 添加主表端点
    $('tbody[master] tr').each(function (i, t) {
        jsPlumb.addEndpoint($(this), $.extend(endpoint, { anchors: ['Right'], isSource: true }));
    });

    // 添加从表端点
    $('tbody[slave] tr').each(function (i, t) {
        jsPlumb.addEndpoint($(this), $.extend(endpoint, { anchors: ['Left'], isTarget: true }));
    });
}

// 删除关联
function removeAssociatio(trIds){
    for (let j = 0; j < relationshipList.length; j++) {
        var line = relationshipList[j];
        var startId = line.start.id;
        var endId = line.end.id;
        if (trIds.indexOf(endId) > -1) {
            line.remove();
            relationshipList.splice(j, 1);
            delete pointList[startId + '_' + endId];
            j = j - 1;
        }
    }
}

function connectField(sourceId, targetId){
    var source =  document.getElementById(sourceId);
    var target = document.getElementById(targetId);
    var key = sourceId + '_' + targetId;
    // 添加 pointList
    pointList[key] = {
        source: source,
        target: target,
        dtConfigId: $("#hid_dtConfigId").val(),
        enumvalue: "",
        fieldid: sourceId.substr(sourceId.indexOf('-') + 1),
        foreignCode: targetId.substr(targetId.indexOf('-') + 1),
        foreignTable: $('#' + targetId).parents('tbody').attr('dtName'), // 通过 targetID 取值
        foreignType: "1",
        relationType: "1", // / 通过 targetID 取值
        remark: ""
    }
    var line = new LeaderLine(
        source,
        target,
        {
            color: '#13227a',
            size: 4,
            startPlug: 'behind',
            endPlug: 'behind',
            startPlugSize: 1,
            endPlugSize: 1,
            dash: { animation: true },
        }
    );
    relationshipList.push(line);
}
function hideConnect() {
    // 隐藏关联表关系
    for (let i = 0; i < relationshipList.length; i++) {
        var lineArrElement = relationshipList[i];
        lineArrElement.hide();
    }
}

function $ajax(url, data, func){
    $.ajax({
        url: postPath + url,
        type: 'POST',
        async: false,
        data: data,
        success: function (data) {
            func && func(data);
        }
    });
}


$(function () {
    systemDataView.prototype.init();
});



//获取参数方法
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

//返回操作
function goback() {
    window.location.href = postPath + "/systemDataViewList/index";
}

function showMsg(text, icon) {
    $.toast().reset('all');
    $.toast({
        text: text,
        icon: icon,
        showHideTransition: 'fade',
        allowToastClose: true,
        hideAfter: 1500,
        stack: false,
        position: 'top-right',
        textAlign: 'left',
        loader: true,
        loaderBg: '#9ec600',
    });
}
